# -*- coding: utf-8 -*-
from abc import ABC

from app.models import db_session
from app.views import CommonHandler
from app.models.dao import add, delete, db2vectors
from app.models.model import TrackModel
from app.tools.utils import distance, THRESHOLD


class TrackHandler(CommonHandler, ABC):
    async def get(self):
        meta_id = self.get_argument("meta_id", None)
        dxftype = self.get_argument("type", None)

        session = db_session()
        features = session.query(TrackModel).filter(
            TrackModel.meta_id == meta_id,
            TrackModel.dxftype == dxftype
        ).all()
        session.close()

        tracks = [feature.vector() for feature in features]

        # 取出tracks里的重复点
        for track in tracks:
            points = [track["points"][0]]
            for i in range(1, len(track["points"])):
                last = len(points) - 1
                x1, y1 = points[last][0], points[last][1]
                x2, y2 = track["points"][i][0], track["points"][i][1]
                if distance(x1, y1, x2, y2) < THRESHOLD:
                    continue
                points.append([x2, y2])
            track["points"] = points

        await self.respose(data=tracks)

    async def post(self):
        params = self.json_params()
        track = TrackModel(params['points'], params['meta_id'])
        track.dxftype = params['type']
        add(track)
        tracks = db2vectors(TrackModel, params['meta_id'])
        await self.respose(data=tracks)

    async def delete(self):
        params = self.json_params()
        delete(TrackModel, params['id'])
        tracks = db2vectors(TrackModel, params['meta_id'])
        await self.respose(data=tracks)